/**
 * 打包-上传到远程服务器脚本
 */

const process = require('child_process');
const FtpDeploy = require("ftp-deploy");
const ftpDeploy = new FtpDeploy();

const config = {
  user: "root",
  password: "gz1995@ATR",
  host: "47.242.153.116",
  port: 22,
  localRoot: __dirname + '/dist',
  remoteRoot: '/www/wwwroot/vmcloud/dist/',
  include: ['*'],
  deleteRemote: false,
  forcePasv: true,
  sftp: true,
};

// 提交代码
const pushCode = () => new Promise((resolve, reject) => {
  process.exec('git pull origin master && git push origin master', (error, stdout, stderr) => {
    if (error) {
      console.log('代码提交失败');
      reject(error);
    } else {
      console.log('代码提交成功');
      resolve();
    }
  });
});

// 构建
const buildProd = () => new Promise((resolve, reject) => {
  process.exec('npm run build', (error, stdout, stderr) => {
    if (error) {
      console.log('构建失败');
      reject(error);
    } else {
      console.log('构建成功');
      resolve();
    }
  });
});

// 连接远程服务器 - 上传文件
const connectServer = () => ftpDeploy
  .deploy(config)
  .then(res => console.log('部署成功'))
  .catch(error => console.log('部署失败', error));

// 开始任务
const startTask = async () => {
  await pushCode();
  await buildProd();
  await connectServer();
};

startTask();
